package org.npu.controller;


import org.apache.ibatis.session.SqlSession;
import org.npu.dao.AdminDao;
import org.npu.entity.Admin;
import org.npu.util.MyBatisUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AdminServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf-8");

        String name = req.getParameter("username");
        String password = req.getParameter("password");

        //获取操作数据库的对象
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        AdminDao dao = sqlSession.getMapper(AdminDao.class);

        int result = dao.AdminLogin(name, password);

        if (result == 1) {

            //管理员登录成功，将管理员用户身份信息存储到session
            Admin admin = dao.queryByNameAndPassword(name,password);
            req.getSession().setAttribute("admin", admin);

            //登录成功
            System.out.println("login successfully!");
            // 在login页面中弹窗”登陆成功“
            resp.setContentType("text/html");
            resp.getWriter().println("<!DOCTYPE html>" +
                    "<html lang='zh'>" +
                    "<head>" +
                    "<meta charset=UTF-8>" +
                    "<meta http-equiv='refresh' content='0; url=/bigweb/adminpage'/>" +
                    "</head>" +
                    "<body>" +
                    "<script>alert('登陆成功!');</script>" +
                    "</body>" +
                    "</html>"
            );
        } else {
            //登录失败
            System.out.println("login failed!");
            // 在login页面中弹窗 ”登陆失败“ 并重定向到登录页面
            resp.setContentType("text/html");
            resp.getWriter().println("<!DOCTYPE html>" +
                    "<html lang='zh'>" +
                    "<head>" +
                    "<meta charset=UTF-8>" +
                    "<meta http-equiv='refresh' content='0; url=/bigweb/admin.html'/>" +
                    "</head>" +
                    "<body>" +
                    "<script>alert('登陆失败!');</script>" +
                    "</body>" +
                    "</html>"
            );
        }
    }
}
